﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace UART1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            COMNUM.SelectedIndex = 2;
            BaudRate.SelectedIndex = 3;
            DataBit.SelectedIndex = 3;
            StopBit.SelectedIndex = 1;
            CheckBit.SelectedIndex = 0;

            CharDisp.Checked = true;
            SendChar.Checked = true;

            CloseComm.Enabled = false;
            DataSend.Enabled = false;
        }

        private void OpenComm_Click(object sender, EventArgs e)
        {
            
            serialPort1.Close();
            serialPort1.PortName = COMNUM.Text;           
            serialPort1.BaudRate = Convert.ToInt32(BaudRate.Text);
            serialPort1.DataBits = Convert.ToInt32(DataBit.Text);
            
            // Downloads By http://www.veryhuo.com
            
            int SPnum = 4;            
            SPnum = StopBit.SelectedIndex;
            switch (SPnum)
            {
                case 0: serialPort1.StopBits = StopBits.None; break;
                case 1: serialPort1.StopBits = StopBits.One; break;
                case 2: serialPort1.StopBits = StopBits.OnePointFive; break;
                case 3: serialPort1.StopBits = StopBits.Two; break;
                default: break;
            }
            SPnum = CheckBit.SelectedIndex;
            switch (SPnum)
            {
                case 0: serialPort1.Parity = Parity.None; break;
                case 1: serialPort1.Parity = Parity.Odd; break;
                case 2: serialPort1.Parity = Parity.Even; break;              
                default: break;
            }
   
            /***************异常处理！****************/
            try
            {
                serialPort1.Open();
            }
            catch (Exception ex)
            {                
                MessageBox.Show("错误："+ex.Message);
            }
            /*****************************************/

            if (serialPort1.IsOpen)
            {               
                CloseComm.Enabled = true;
                DataSend.Enabled = true;

                OpenComm.Enabled = false;
                COMNUM.Enabled = false;
                BaudRate.Enabled = false;
                DataBit.Enabled = false;
                StopBit.Enabled = false;
                CheckBit.Enabled = false;
            }

        }

        private void CloseComm_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Close();

                CloseComm.Enabled = false;
                DataSend.Enabled = false;

                OpenComm.Enabled = true;
                COMNUM.Enabled = true;
                BaudRate.Enabled = true;
                DataBit.Enabled = true;
                StopBit.Enabled = true;
                CheckBit.Enabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show("错误：" + ex.Message);

                CloseComm.Enabled = true;
                DataSend.Enabled = true;

                OpenComm.Enabled = false;
                COMNUM.Enabled = false;
                BaudRate.Enabled = false;
                DataBit.Enabled = false;
                StopBit.Enabled = false;
                CheckBit.Enabled = false;
            }

        }

        private void DataSend_Click(object sender, EventArgs e)
        {
            string InputString = SendBox.Text;
    
            /**********发送byte[]实例*********/
            //byte[] SendBytes = new byte[]{0xff,0xe0,0xd0,0xc0,0xb0,0xa0,0x90,0x80,0x70,0x60};
            //int DatasLength = SendBytes.Length;
            //serialPort1.Write(SendBytes, 0, DatasLength);
            /*******************************/
            
            
            if (SendChar.Checked == true)  //以字符形式发送，直接发送字符串
            {
                try
                {
                    
                    char[] SendChars = InputString.ToCharArray();
                    int CharsLength = SendChars.Length;

                    serialPort1.Encoding = System.Text.Encoding.GetEncoding("GB2312");  //解决中午乱码问题，国标2312编码格式
                    serialPort1.Write(SendChars, 0, CharsLength);

                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误：" + ex.Message);
                }
            }
            else
            {
                if (SendHEX.Checked == true)  //以HEX形式发送，输入范围：0~255，即0~FF。
                {
                    try
                    {
                        byte SendByte = Convert.ToByte(InputString);
                        try 
                        {
                            serialPort1.Write(String.Format("{0:X}",SendByte));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("错误：" + ex.Message);
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("请输入0~255，即0x00~0xFF！");
                    }
                }
            }
             
        }

        private void SerialPortDataReceive(object sender, SerialDataReceivedEventArgs e)
        {
            int ReceiveNums = serialPort1.BytesToRead;

            if (HEXDisp.Checked == true)
            {
                
                for (int i = 0; i < ReceiveNums; i++)
                {
                    ReceiveBox.AppendText(String.Format("{0:X2} ", serialPort1.ReadByte()));
                }
  
            }
            else 
            {
                if (CharDisp.Checked == true)
                {                   
                    /*
                    for (int i = 0; i < ReceiveNums; i++)
                    {
                        ReceiveBox.AppendText(String.Format("{0:X2}", Convert.ToChar(serialPort1.ReadByte())));
                    }*/
                    serialPort1.Encoding = System.Text.Encoding.GetEncoding("GB2312");//解决中午乱码问题，国标2312编码格式
                    ReceiveBox.AppendText(serialPort1.ReadExisting());
                }
            }   
            
        }

        private void ClearSend_Click(object sender, EventArgs e)
        {
            SendBox.Clear();
        }

        private void ClearReceive_Click(object sender, EventArgs e)
        {
            ReceiveBox.Clear();
        }
        
        private void Exit_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Close();
            }
            catch (TimeoutException ex)
            {
                MessageBox.Show("错误：" + ex.Message);
            }
            Close();
        }

    }
}
